from django.db import models
from django.utils import timezone

class APICallStatistics(models.Model):
    """API调用统计模型"""
    path = models.CharField(max_length=255, verbose_name='API路径')
    method = models.CharField(max_length=10, verbose_name='请求方法')
    status_code = models.IntegerField(verbose_name='状态码')
    response_time = models.FloatField(verbose_name='响应时间(ms)')
    ip_address = models.GenericIPAddressField(verbose_name='IP地址')
    user_agent = models.TextField(verbose_name='User Agent')
    user = models.ForeignKey('users.User', on_delete=models.SET_NULL, null=True, verbose_name='用户')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='调用时间')
    request_data = models.JSONField(null=True, blank=True, verbose_name='请求数据')
    response_data = models.JSONField(null=True, blank=True, verbose_name='响应数据')

    class Meta:
        verbose_name = 'API调用统计'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['path']),
            models.Index(fields=['method']),
            models.Index(fields=['status_code']),
            models.Index(fields=['created_at']),
            models.Index(fields=['user']),
        ]

    def __str__(self):
        return f"{self.method} {self.path} - {self.status_code}"